﻿using System.Diagnostics;
using System.Threading;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;

namespace WinRT.SIP.Tasks
{
    public sealed class IncomingCallTask : IBackgroundTask
    {
        BackgroundTaskDeferral _deferral = null;
        IBackgroundTaskInstance _taskInstance = null;

        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");

            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler((sender, reason) =>
                {
                });

            _deferral = taskInstance.GetDeferral();
            _taskInstance = taskInstance;

            ToastAlarm();
            //while (true)
            //{
            //    using (EventWaitHandle tmpEvent = new ManualResetEvent(false))
            //    {
            //        ToastAlarm();
            //        tmpEvent.WaitOne(60000);
            //    }
            //}
        }

        void ToastAlarm()
        {
            XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
            // Toasts can optionally be set to long duration by adding the 'duration' attribute
            IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
            ((XmlElement)toastNode).SetAttribute("duration", "long");
            ((XmlElement)toastNode).SetAttribute("launch", "Fat Albert");

            // This XmlNodeList will have two items since the template we are using has two text fields.
            XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
            stringElements.Item(0).AppendChild(toastXml.CreateTextNode("Incoming Call"));

            XmlElement audioElement = toastXml.CreateElement("audio");

            // Long-duration Toasts can optionally loop audio using the 'loop' attribute
            audioElement.SetAttribute("src", "ms-winsoundevent:Notification.Looping.Alarm");
            audioElement.SetAttribute("loop", "true");
            stringElements.Item(1).AppendChild(toastXml.CreateTextNode("Fat Albert"));

            toastNode.AppendChild(audioElement);

            ToastNotification toast = new ToastNotification(toastXml);
            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
    }
}
